#-*- coding: utf-8 -*-
'''
Created on Jun 24, 2012

@author: bbg
'''

from logic.login_session_mgr import LoginSessionMgr
from logic.cdkey_mgr import CdkeyManager 
from core.db.companyx.user_right import UserRight
from core.db.companyx.user import User
from core.db.companyx.login_session import LoginSession
from service.server_config import SrvConfig
from core.util.debug import Log
import uuid
from webob import Request, Response

def application(environ, start_response):
    '''
        entrance of apache wsgi application
    '''    
    req = Request(environ)
    res = Response()
    
    CdkeyService.process(req, res)
    
    return res(environ, start_response)



class CdkeyService(object):
    
    __setup__ = False
    log = None    

    @staticmethod
    def process(req, res):
        '''
            0. 激活
            1 权限验证
        '''
        if CdkeyService.__setup__ == False:
            Log.setPath(SrvConfig.getLogPath())
            CdkeyService.log = Log()            
            CdkeyService.__setup__ = True           
                  
        try:
            dbsession = SrvConfig.getDefaultDBSession()
                
            cdkeyService = CdkeyService(dbsession)
            reqType = req.params['type']
            if reqType == '0': # client激活CDKEY
                cdkeyService.active(req, res)
            elif reqType == '1': # client通过cdkey验证是否有某项权限
                cdkeyService.authenticate(req, res)
            else:
                res.json = {'ret':-1, 'msg':'invalid login type:%d' % reqType}
    
        except Exception,e:
            CdkeyService.log.e("CdkeyService:process, exception:%s" % e)
            res.json = {'ret':-1, 'msg':'CdkeyService:process exception'}
        finally:
            dbsession.close()
        
            
    def __init__(self, dbsession):
        self.dbsession = dbsession
            

    def _checkParams(self, req):
        '''
           检查各个参数是否合法
        '''
        try:
            cdkey = req.params['cdkey']
            uuid = req.params['uuid']
            username = req.params['username']
            pwd = req.params['pwd']
            company_id = req.params['company_id']
            shop_id = req.params['shop_id']
        
            if cdkey == None or uuid == None or username == None or company_id == None or shop_id == None or pwd == None:
                return (-1, '参数不完整')
        
            #判断企业ID是否合法
            intcomp = LoginSessionMgr.isValidCompanyid(company_id, self.dbsession)
            if intcomp == False:       
                return (-1,"企业不存在")
           
            #check cdkey mapping
            dbmap = CdkeyManager.getCompanyShopIdPair(cdkey, self.dbsession)
            CdkeyService.log.d("CdkeyService: map to campany_id,shop_id:%s" % repr(dbmap))
       
            if dbmap == None:
                return (103, "无效的cdkey")
        
            if int(dbmap[0]) != int(company_id) or int(dbmap[1]) != int(shop_id):
                return (-2, "输入的企业ID和店铺ID无效")
         
            #判断当前的CDKEY的状态：已经激活或者已经过期 或者该UUID 不为空都返回
            state = dbmap[2]
            if state == 1:
                return (104, "cdkey 已经激活，不可以重新激活")
        
            if state=="2":
                return (105, "cdkey 已经过期，不可以重新激活")
                           
            if CdkeyManager.checkhasCompanyUUID(uuid, self.dbsession) is True:
                return (106, "UUID已经绑定，不可以重复绑定")
            
            #判断帐号和密码是否正确
            LoginSession.doMapping(company_id)
            User.doMapping(company_id)                 
            users = self.dbsession.query(User).filter(User.name == username)
            if users.count() == 0:
                return (-1, '用户名不存在')
               
            if users.first().pwd != pwd:
                return (-2, '密码不正确')

            return (0,'ok')
        except Exception, e:
            CdkeyService.log.e("CdkeyService:_checkParams, exception:%s" % e)
            return (-3, '参数不正确')
        
        return (-1, 'unknown error')  
         

    def active(self, req, res):
        '''
              负责客户端激活CDKEY 
        '''
        ret = self._checkParams(req)

        if ret[0] != 0:
            res.json = {'ret':ret[0], 'msg': ret[1]}
            return
        
        cdkey = req.params['cdkey']
        uuid = req.params['uuid']
                             
        bindResult = CdkeyManager.bindUuidCDkey(cdkey, uuid, self.dbsession)
        
        if bindResult is None:
            #response cdkey invalid, login failed
            CdkeyService.log.e('CdkeyService:active, error %s' % cdkey)
            res.json = {'ret':-1, 'msg':'激活CDKEY失败'}
            return
        
        res.json = {
                    'ret':0, 
                    'msg':'success',
                    'company_id': bindResult[0],
                    'shop_id': bindResult[1],
                    'uuid': bindResult[2],
                    'cdkey': bindResult[3]
                    }
 

    def authenticate(self, req, res):
        '''
            负责客户端权限验证 
        '''

        uuid = req.params['uuid']
        cdkey= req.params['cdkey']
        username = req.params['username'] 
        userid = req.params['userid']     
        right_name = req.params['right_name']  
        token = req.params['token']
 
        if uuid == None or cdkey == None or username == None or userid == None or right_name == None or token == None:
            res.json = {'ret':-1, 'msg':'参数不完整'}
            return
            
        #匹配CDKEY 并返回企业ID和SHOPID hasbindUuidCDkey
        bindResult = CdkeyManager.hasbindUuidCDkey(cdkey, uuid, self.dbsession)
        if bindResult == None:
            res.json = {'ret':-1, 'msg':'CDKEY无法匹配'}
            return 
        
        company_id = bindResult[0]    
        #检查TOKEN是否过期
        isValid = LoginSessionMgr.isSessionValid(company_id, username, token, self.dbsession)        
        if isValid == False:
            res.json = {'ret':-1, 'msg':'TOKEN 已经过期'}
            return            

        #最后判断权限是否拥有
        UserRight.doMapping(company_id)
        userRight = self.dbsession.query(UserRight).filter(UserRight.user_id == userid and UserRight.right_name == right_name)
    
        if userRight.count() == 0:
            res.json = {'ret':-1, 'msg':'没有权限'}
            return

        res.json = {'ret':0, 'msg':'有权限'}
        
